package com.dongan.service.impl;
import com.dongan.mapper.MenusMapper;
import com.dongan.pojo.Codes;
import com.dongan.mapper.CodesMapper;
import com.dongan.pojo.Menus;
import com.dongan.service.CodesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dongan.service.MenusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author longTao
 * @since 2021-06-15
 */
@Service
public class MenusServiceImpl extends ServiceImpl<MenusMapper, Menus> implements MenusService {
    @Autowired
    private MenusMapper mapper;

    /**
     * 查询全部菜单
     *
     * @return
     */
    @Override
    public List<Menus> queryList() {
        List<Menus> menus = mapper.selectList(null);
        List<Menus> list = queryItsSecondaryMenu(menus);
        return list;
    }

    /**
     * 根据角色id查询出菜单
     *
     * @param id
     * @return
     */
    @Override
    public List<Menus> queryMenu(Long id) {
        List<Menus> menus = mapper.queryByRoleId(id);
        List<Menus> menusList = queryItsSecondaryMenu(menus);
        return menusList;
    }

    /**
     * 查询出它的子菜单
     * @param menus
     * @return
     */
    private List<Menus> queryItsSecondaryMenu(List<Menus> menus){
        List<Menus> list=new ArrayList<>();
        for (Menus menu : menus) {
            if (menu.getParentId()==0){
                list.add(queryAllItsSubmenus(menus,menu));
            }
        }
        return list;
    }

    /**
     * 递归查询出它所有的子菜单
     * @param list
     * @param menus
     * @return
     */
    private Menus queryAllItsSubmenus(List<Menus> list,Menus menus){
        for (Menus m : list) {
            if (menus.getId().longValue()==m.getParentId().longValue()){
              if (menus.getList()==null){
                  menus.setList(new ArrayList<>());
              }
              menus.getList().add(queryAllItsSubmenus(list,m));
            }
        }
        return menus;
    }
}
